package com.vehicle.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.vehicle.bean.ResultDto;
import com.vehicle.pojo.User;
import com.vehicle.service.UserService;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
@RequestMapping("/loginController")
public class LoginController {
    @Autowired
    private UserService userService;
    private Logger logger=Logger.getLogger(this.getClass());

    @ResponseBody
    @GetMapping(value = "/login")
    public ResultDto login(@RequestParam("uname")String uname, @RequestParam("password")String password ){
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        ResultDto resultDto=null;
        User u= userService.findUserByUid(uname,password);
        if(u==null){
            return new ResultDto("账号或密码错误",1002,"账号密码错误",null);
        }
        if (u!=null&&u.getAvailable()==0){
            return new ResultDto("用户已禁用",1001,"用户已禁用",null);
        }

        UsernamePasswordToken token = new UsernamePasswordToken(uname, password);

        subject.login(token);
        if (subject.isAuthenticated()){
            User user =userService.findUserByUid(uname,password);

            session.setAttribute("USER_SESSION",user);
            resultDto=new ResultDto("登陆成功",200,null,user);
        }else {
            resultDto=new ResultDto("用户名或密码错误",10001,"用户名或密码",null);
        }
        return resultDto;

    }
    @RequestMapping(value = "/loginOut")
    public String loginOut(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "/page/login.jsp";
    }
    @ResponseBody
    @RequestMapping("/getCode")
    public void getCode(HttpServletResponse response) throws IOException {
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        //HuTool定义图形验证码的长和宽,验证码的位数，干扰线的条数
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(116, 36,4,10);
        //将验证码放入session
        String code=lineCaptcha.getCode();
        logger.info(code);
        session.setAttribute("CODE",code);
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            lineCaptcha.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
